package com.baway.home.view

import android.util.Log
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.baway.base.path.RouterPath
import com.baway.common.entity.BannerEntity
import com.baway.common.entity.NoticeEntity
import com.baway.common.entity.ServiceEntity
import com.baway.common.event.CustomEvent
import com.baway.common.view.BaseMvvmFragment
import com.baway.home.R
import com.baway.home.adapter.HomeBannerAdapter
import com.baway.home.adapter.HotServiceAdapter
import com.baway.home.adapter.NoticeListAdapter
import com.baway.home.databinding.FragmentHomeBinding
import com.baway.home.vm.HomeViewModel
import com.blankj.utilcode.util.GsonUtils
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.transformer.AlphaPageTransformer
import dagger.hilt.android.AndroidEntryPoint


@Route(path = RouterPath.PATH_HOME_PAGE)
@AndroidEntryPoint
class HomeFragment : BaseMvvmFragment<FragmentHomeBinding>() {

    //在Fragment中使用activityViewModels()函数，在Activity中viewModels()函数
    private val mViewModel: HomeViewModel by activityViewModels()

    private val keyWords = arrayListOf("热门公告", "节日彩蛋", "园区新闻")

    private val bannerData = mutableListOf(
        BannerEntity(0, R.drawable.home_banner_0, ""),
        BannerEntity(0, R.drawable.home_banner_1, ""),
        BannerEntity(0, R.drawable.home_banner_2, ""),
    )

    private val hotServiceData = mutableListOf(
        ServiceEntity(R.drawable.icon_hot_service_0, "", "车位管理", 0),
        ServiceEntity(R.drawable.icon_hot_service_1, "", "访客登记", 1),
        ServiceEntity(R.drawable.icon_hot_service_2,"", "物业报修", 2),
        ServiceEntity(R.drawable.icon_hot_service_3,"", "考勤打卡", 3),
        ServiceEntity(R.drawable.icon_hot_service_4,"", "房源信息", 4),
        ServiceEntity(R.drawable.icon_hot_service_5,"", "商家推荐", 5),
        ServiceEntity(R.drawable.icon_hot_service_6,"", "月卡会员", 6),
        ServiceEntity(R.drawable.icon_hot_service_7,"", "设备管理", 7),
    )

    private lateinit var noticeListAdapter: NoticeListAdapter
    private lateinit var serviceListAdapter: HotServiceAdapter
    private val noticeList = mutableListOf<NoticeEntity>()

    private var pageIndex = 0
    private val pageSize = 10

    override fun getLayoutId(): Int = R.layout.fragment_home

    override fun initViews() {
        //mDataBinding.includeTopTitle


        //设置搜索框中热词
        mDataBinding.tvbSearch.run {
            setDatas(keyWords)
            setItemOnClickListener { data, _ ->
                ARouter.getInstance().build(RouterPath.PATH_SEARCH_PAGE).withString("hotWords", data).navigation()
            }
        }

        //设置Banner
        mDataBinding.bannerV2.run {
            setAdapter(HomeBannerAdapter(bannerData))
            setPageTransformer(AlphaPageTransformer())
            setIndicator(CircleIndicator(this@HomeFragment.requireContext()))
            addBannerLifecycleObserver(this@HomeFragment.viewLifecycleOwner) //关联Fragment生命周期
        }

        //设置热门服务
        serviceListAdapter = HotServiceAdapter(hotServiceData).apply {
            setItemOnClickListener(object : HotServiceAdapter.ItemOnClickListener{
                override fun onClick(v: View, position: Int) {
                    this@HomeFragment.dispatchServicePage(hotServiceData[position])
                }
            })
        }

        mDataBinding.rvHotService.run {
            layoutManager = GridLayoutManager(this@HomeFragment.requireContext(), 4)
            adapter = serviceListAdapter
        }



        //设置公告列表数据
        noticeListAdapter = NoticeListAdapter(noticeList)
        mDataBinding.rvNotice.run {
            layoutManager = LinearLayoutManager(this@HomeFragment.requireContext(),LinearLayoutManager.VERTICAL, false)
            adapter = noticeListAdapter
        }
    }

    /**
     * 分发服务页面
     */
    private fun dispatchServicePage(service: ServiceEntity){
        var pagePath = when(service.typeId){
            0 -> RouterPath.PATH_PARK_PAGE      //车位管理
            1 -> RouterPath.PATH_VISITOR_PAGE   //访客登记
            2 -> RouterPath.PATH_REPAIR_PAGE    //物业报修
            3 -> RouterPath.PATH_PUNCH_PAGE     //考勤打卡
            4 -> RouterPath.PATH_HOUSE_PAGE     //房源信息
            5 -> RouterPath.PATH_MERCHANT_PAGE  //商家推荐
            6 -> RouterPath.PATH_VIP_PAGE       //月卡会员
            7 -> RouterPath.PATH_DEVICE_PAGE    //设备管理
            else -> RouterPath.PATH_EMPTY_PAGE
        }
        ARouter.getInstance().build(pagePath).navigation()
    }

    override fun loadData() {
        mViewModel.loadNoticeData(pageIndex, pageSize)
    }

    override fun observeDataChanged() {
        mViewModel.mSuccess.observe(this@HomeFragment.requireActivity()){
            if (!it.isNullOrEmpty()){
                noticeList.addAll(it)
                noticeListAdapter.notifyDataSetChanged()
            } else{
                pageIndex = if (pageIndex > 0) pageIndex - 1 else pageIndex
            }
        }

        mViewModel.mUserInfo.observe(this@HomeFragment){

            Log.i("======", "本地数据库存储的用户信息："+GsonUtils.toJson(it))

        }
    }

    override fun handEvent(event: CustomEvent) {
        Log.i("======", "查询数据库用户信息：")
        //判断登录成功业务
        if (event.type == 100){
            mViewModel.queryUserInfoFormRoom(event.data as Int)
        }

    }



}